//Nicccce
import React, {Component} from 'react';
import NavigationBar from '../../Common/NavigationBar/NavigationBar.jsx';
import WeUI from 'react-weui';
import {CSS} from '../styles/userInfo.css';
import EXIF from '../../../assets/js/exif.js';
import $ from 'jquery';
const {
    CellsTitle,
    Cells,
    Cell,
    CellHeader,
    CellBody,
    CellFooter,
    Label,
    Input,
    Button,
    Toast,
    Toptips,
    ButtonArea,
    Dialog,
} = WeUI;
const info_btn = {
    position: 'absolute',
    borderRadius: '5px',
    background: '#0088EC',
    bottom: '6rem',
    left: '2rem',
    right: '2rem',
};
const basic_input = {
    fontSize: "1.7rem",
    color: "#000000",
};
let height = document.body.clientHeight;
//算高
let screenWidth = $(window).width();
let screenHeight = $(window).innerHeight();
let baseFontSize = 10 * screenWidth / 375;
export default class SetName extends Component {
    constructor(props) {
        super(props);
        this.LeftClick = this.LeftClick.bind(this);
        this.SaveClick = this.SaveClick.bind(this);
        this.state = {
            from: this.props.location.query.from,
            showLoading: true,
            showToast: false,
            toastTimer: null,
            showWarn: false,
            warnTimer: null,
            topTipsMsg:"服务异常!",
            tipText: "",
            userName: "",
            first: true,
            showDialog:false,
            userInfo:{},
            dialogStyle: {
                title: "人脸使用说明",
                buttons: [
                    {
                        label: '确定',
                        onClick: this.hideDialog.bind(this)
                    }
                ]
            },


            image:null,

        };
    }

    hideDialog() {
        this.setState({
            showDialog: false
        })
    }

    showWarn(error) {
        this.setState({showWarn: true,topTipsMsg:error, showLoading: false});
        this.state.warnTimer = setTimeout(() => {
            this.setState({showWarn: false});
        }, 2000);
    }

    showToast() {
        this.setState({showToast: true,showLoading:false});
        this.state.toastTimer = setTimeout(()=> {
            this.setState({showToast: false});
            if (this.state.from) {
                location.hash = "/" + this.state.from;
            } else {
                location.hash = "/UserCenter";
            }

        }, 1000);
    }

    componentWillMount() {
        this.state.toastTimer && clearTimeout(this.state.toastTimer);
        window.addEventListener('resize', this.onWindowResize.bind(this))

    }

    componentWillUnmount() {
        window.removeEventListener('resize', this.onWindowResize.bind(this))
    }

    componentDidMount() {
       this.getUserInfo()
    }


    getUserInfo(){
        //获取个人信息
        let self = this;
        fetch(getHost() + "/user/detail",{
            credentials: 'include'
        }).then(response => response.json())
            .then(d => {
                if (d.success) {
                    self.setState({userInfo:d.data,showLoading:false,userName:d.data.nickyName});
                } else {
                    self.showWarn(d.error.message);
                }
        });
    }
    LeftClick() {

    }
    //监听键盘弹起
    onWindowResize(){
        let h = document.body.clientHeight;
        if(h < height){
            $(".setName_footer_btn").hide();
        }else{
            $(".setName_footer_btn").show();
        }
    }

    //上传图片
    uploadFile() {
        $("#uploadFile").trigger('click');
    }

    imagePreview(e) {
        if (e) {
            let file = e.target.files[0];
            if (!this.checkFile(file.type)) {
                this.showWarn("图片格式错误");
                return;
            }
            let self = this;
            //读取图片数据
            // alert(file.size / 1024);
            var reader = new FileReader();
            reader.onload = function (e) {
                var data = e.target.result;
                //加载图片获取图片真实宽度和高度
                var image = new Image();
                image.onload = function () {
                    var maxSize = 400; // 400k
                    var fileSize = file.size / 1024; // 图片大小
                    let uploadSrc = self.rotateImage(image, file.type, maxSize, fileSize);
                    let uploadFile = self.convertBase64UrlToFile(uploadSrc, file.name); // 转成file文件
                    self.refs.staffHeader_img.src = uploadSrc;
                    self.state.image = uploadFile;
                };
                image.src = data;
            };
            reader.readAsDataURL(file);
        }
    }
    /**
     * 检查文件是否为图像类型
     * @param files         FileList
     * @returns file        File
     */
    checkFile(type) {
        //使用正则表达式匹配判断
        if (!/image\/\w+/.test(type)) {
            return false;
        } else {
            return true;
        }
    }

    //获取图片方向
    getPhotoOrientation(img) {
        var orient;
        EXIF.getData(img, function () {
            orient = EXIF.getTag(this, 'Orientation');
        });
        return orient;
    }


    //图片旋转
    rotateImage(img, type, maxSize, fileSize) {
        let canvas, ctx, img64, orient;
        let width = img.width;
        let height = img.height;
        //获取图片方向
        orient = this.getPhotoOrientation(img);

        canvas = document.createElement('canvas');
        ctx = canvas.getContext("2d");
        ctx.save();
        //如果图片方向等于6 ，则旋转矫正，反之则不做处理
        switch (orient) {
            case 1:
                console.log('旋转0°');
                canvas.width = width;
                canvas.height = height;
                break;
            case 6:
                console.log('旋转90°');
                canvas.width = height;
                canvas.height = width;
                ctx.rotate(Math.PI / 2);
                ctx.translate(0, -height);

                break;
            case 3:
                console.log('旋转180°');
                canvas.height = height;
                canvas.width = width;
                ctx.rotate(Math.PI);
                ctx.translate(-width, -height);

                break;
            case 8:
                console.log('旋转270°');
                canvas.height = width;
                canvas.width = height;
                ctx.rotate(3 * Math.PI / 2);
                ctx.translate(-width, 0);

                break;
            default:
                console.log('undefined  不旋转');
                canvas.width = width;
                canvas.height = height;
                break;


        }
        ctx.drawImage(img, 0, 0);
        ctx.restore();
        if (fileSize > maxSize) {
            img64 = canvas.toDataURL(type, maxSize / fileSize);
        } else {
            img64 = canvas.toDataURL(type, 0.5);
        }

        return img64;
    }

    /**
     * 校验图片转换后大小并上传
     */
    checkAndHandleUpload(file) {
        let self = this;
        this.imgBase64(file, function (image, canvas) {
            var maxSize = 400; // 400k

            var fileSize = file.size / 1024; // 图片大小
            let uploadSrc = '';
            let uploadFile = null;
            if (fileSize > maxSize) { // 如果图片大小大于400k，进行压缩
                console.log(maxSize, fileSize, maxSize / fileSize);
                uploadSrc = canvas.toDataURL(file.type, maxSize / fileSize);
                uploadFile = self.convertBase64UrlToFile(uploadSrc, file.name); // 转成file文件
            } else {
                uploadSrc = image.src; //canvas.toDataURL(file.type,0.5);
                uploadFile = file;
            }

            var compressedSize = uploadFile.size / 1024;
            // alert(compressedSize.toFixed(2));
            if (compressedSize.toFixed(2) > 400) {
                self.checkAndHandleUpload(uploadFile);
            } else {
                self.refs.staffHeader_img.src = uploadSrc;
                self.state.image = uploadFile;
            }
        });
    }

    /**
     * 将图片转化为base64
     */
    imgBase64(file, callback) {
        var self = this;
        // 看支持不支持FileReader
        if (!file || !window.FileReader) return;
        // 创建一个 Image 对象
        var image = new Image();
        // 绑定 load 事件处理器，加载完成后执行
        image.onload = function () {
            // 获取 canvas DOM 对象
            var canvas = document.createElement('canvas')
            // 返回一个用于在画布上绘图的环境, '2d' 指定了您想要在画布上绘制的类型
            var ctx = canvas.getContext('2d')
            // 如果高度超标 // 参数，最大高度
            var MAX_HEIGHT = 3000;
            if (image.height > MAX_HEIGHT) {
                // 宽度等比例缩放 *=
                image.width *= MAX_HEIGHT / image.height;
                image.height = MAX_HEIGHT;
            }
            // 获取 canvas的 2d 环境对象,
            // 可以理解Context是管理员，canvas是房子
            // canvas清屏
            console.log('canvas.width:', canvas.width);
            ctx.clearRect(0, 0, canvas.width, canvas.height);
            // 重置canvas宽高
            canvas.width = image.width;
            canvas.height = image.height;
            // 将图像绘制到canvas上

            ctx.drawImage(image, 0, 0, image.width, image.height);
            // !!! 注意，image 没有加入到 dom之中

            console.log(file.type);
            // console.log(canvas.toDataURL('image/jpeg',0.5));
            //----------//
            callback(image, canvas);
            //--------//
        };
        if (/^image/.test(file.type)) {
            // 创建一个reader
            var reader = new FileReader();
            // 读取成功后的回调
            reader.onload = function () {
                // self.imgUrls.push(this.result);
                // 设置src属性，浏览器会自动加载。
                // 记住必须先绑定事件，才能设置src属性，否则会出同步问题。
                image.src = this.result;
            }
            // 将图片将转成 base64 格式
            reader.readAsDataURL(file);
        }

    }

    /**
     * 将以base64的图片url数据转换为file
     *            用url方式表示的base64图片数据
     */

    convertBase64UrlToFile(dataurl, filename) {//将base64转换为文件
        var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
            bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
        while (n--) {
            u8arr[n] = bstr.charCodeAt(n);
        }
        // let newName=Date.parse(new Date())+".jpeg";
        return new File([u8arr], filename, {type: mime});
    }

    //确认加入
    confirmAdd(){


    }

    SaveClick() {

        let self = this;
        let fromData = new FormData();
        let newName = document.getElementById("newName").value.replace(/^\s+|\s+$/g, '');//
        if(newName.length === 0){
            this.showWarn("请输入正确名字");
            return;
        }
        if (newName.length === 0 && !this.state.image){
            this.showWarn("请输入有效内容");
            document.getElementById("newName").value = "";
            return;
        }
        if(this.state.image){
            fromData.append("picture",this.state.image);
        }
        if(newName){
            fromData.append("nickyName", newName);
        }
        this.setState({showLoading:true});
        fetch(getHost() + "/user/modify", {
            method: 'POST',
            credentials: 'include',
            body: fromData
        }).then(response => response.json()).then(d => {
            if (d.success) {
                self.showToast();
            } else {
                self.showWarn(d.error.message);
            }
        }).catch(e => {
            self.showWarn("服务错误!");
        });
    }

    //监听输入框输入
    setUserName(e){
        this.setState({userName:e.target.value});

    }
    render() {
        let remainHeight = screenHeight - (5.2+ 2.7 + 5.6) * baseFontSize  + "px";
        return (
            <div>
                <NavigationBar Title="设置姓名" LeftBar="true" LeftTitle="返回"
                               LeftIconSrc="/iot-meeting/assets/images/common/nav_back_icon.png" LeftClick={this.LeftClick}/>
                <div className="setName_content_box" style={{height:remainHeight}}>
                    <CellsTitle className="title_text">设置姓名</CellsTitle>
                    <Cells>
                        <Cell>
                            <CellHeader>
                                <Label>姓名</Label>
                            </CellHeader>
                            <CellBody>
                                <Input id="newName" style={basic_input} type="text" placeholder="（20字内）" maxLength="20"  onChange={this.setUserName.bind(this)}  value={this.state.userName ? this.state.userName : ""}/>
                            </CellBody>
                        </Cell>
                        <Cell>
                            <CellHeader>
                                <Label>电话</Label>
                            </CellHeader>
                            <CellBody>
                                <div className="mobile_userInfo">{this.state.userInfo.mobile ? this.state.userInfo.mobile  : ""}</div>
                            </CellBody>
                        </Cell>
                    </Cells>
                    <div className="basicTips">电话将作为本人的登录账号，不可修改。</div>
                    <div className="file_box">
                        <img className="staffHeader_img" ref="staffHeader_img" src={this.state.userInfo.localVerifyFaceUrl? this.state.userInfo.localVerifyFaceUrl : '/iot-meeting/assets/images/header_img.png'}/>
                        <button className="uploader_button" onClick={this.uploadFile.bind(this)}>点击上传</button>
                        <input type="file" style={{display: "none"}} id="uploadFile" onChange={this.imagePreview.bind(this)}
                               accept="image/*"/>
                    </div>
                    <div className="hint_title">请上传员工的清晰正面照，建议光线充足且人脸完整。</div>
                    <div className="header_box">
                        <div className="header_title" onClick={e => this.setState({showDialog: true})}>人脸用途与隐私说明</div>
                        <img className="hint_img" src='/iot-meeting/assets/images/hint_img.png'/>
                    </div>
                </div>
                <div className="setName_button_box">
                    <ButtonArea direction="horizontal">
                        <Button  onClick={this.SaveClick}>确认保存</Button>
                    </ButtonArea>
                </div>
                {/*<div style={info_btn} className="setName_footer_btn">*/}
                    {/*<Button onClick={this.SaveClick}>确认保存</Button>*/}
                {/*</div>*/}
                <Dialog title={this.state.dialogStyle.title} buttons={this.state.dialogStyle.buttons}
                        show={this.state.showDialog}>
                    <div>
                        <div className="faceTip_title">此人脸仅用于出入包括：办公室、会议室等园区空间。</div>
                        <div className="faceTip_title">将不会泄露您的个人隐私。</div>
                    </div>
                </Dialog>
                <Toast icon="loading" show={this.state.showLoading}>加载中...</Toast>
                <Toast icon="success-no-circle" show={this.state.showToast}>修改成功</Toast>
                <Toptips type="warn" show={this.state.showWarn}>
                    {this.state.topTipsMsg}
                </Toptips>
            </div>
        )
    }
}
